<?php

class SlideController extends BackendController
{
	public $parentUrl;
	
	public function init(){
		parent::init();
		$this->parentUrl = $this->module->id . '/' . Yii::app()->getController()->getId();
	}


	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','delete'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	public function actionCreate()
	{
		try {
            $model = new Slide();      
            $content = new Content();      
            if (isset($_POST['Slide'])) {
                $content['Short_Descriptions'] = $_POST['Content']['Short_Descriptions'];
                $content['Descriptions'] = $_POST['Content']['Descriptions'];
                $content['CreateDate'] = date('Y-m-d H:i:s');
                //$content['UpdateDate'] = date('Y-m-d H:i:s');
 				$content->save();
 				$content_id = $content['ContentId'];
                $model->attributes = $_POST['Slide'];
                $model['ContentId'] = $content_id;
                $model->SlideNameRewrite = str_replace(" ", "-", strtolower(StringHelper::remove_vietnamese_accents($model->SlideName)));
                $cover_image = CUploadedFile::getInstance($model, 'SlidePhotoName');
                if ($cover_image)
                    $model->SlidePhotoName = 'slide_' . md5(time()) . '.' . $cover_image->getExtensionName();
                
                $model->validate();
              	if ($cover_image) {
                    $model->SlidePhotoName = MyFunctionCustom::saveSlide($model, $cover_image);
                    $model->SlideOldPhoto = $cover_image->name;
                }
                $model->save();
	            $this->redirect(Yii::app()->createAbsoluteUrl(Yii::app()->baseUrl . '/store/backend/slide/index'));
            }

            $this->render('create', array(
                'model' => $model,
                'content' => $content,
            ));
        } catch (Exception $e) {
            Yii::log("Invalid request. Please do not repeat this request again.");
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
	}

	public function actionUpdate($id)
	{
		try {
            $model = $this->loadModel($id);
            $content = Content::model()->findByPk($model->ContentId);
            if (isset($_POST['Slide'])) {
            	//var_dump($_POST['Slide']);die;
            	$oldCover = $model->CoverPhoto;
            	$content->attributes = $_POST['Content'];
                $content['UpdateDate'] = date('Y-m-d H:i:s');
                $content->save();
                $model->attributes = $_POST['Slide'];
                $cover_image = '';
                $model->SlideNameRewrite = str_replace(" ", "-", strtolower(StringHelper::remove_vietnamese_accents($model->SlideName)));
                if($_POST['Slide']['SlidePhotoName']){
                	$cover_image = CUploadedFile::getInstance($model,'SlidePhotoName');
                }
                if ($cover_image)
                    $model->SlidePhotoName = 'silde_' . md5(time()) . '.' . $cover_image->getExtensionName();
                else{
                	$model->CoverPhoto = $oldCover;
                }
                $model->validate();                
                if (!$model->hasErrors()) {
                    if ($cover_image) {
                        //delete File
                        MyFunctionCustom::DeleteFile($model, 'SlidePhotoName', 'slide');
                        $model->SlidePhotoName = MyFunctionCustom::saveSlide($model, $cover_image);
                        $model->SlideOldPhoto = $cover_image->name;
                    }
                    $model->save();
	                $this->redirect(Yii::app()->createAbsoluteUrl(Yii::app()->baseUrl . '/store/backend/slide/index'));
                }
            }
            $this->render('update', array(
                'model' => $model,
                'content' => $content,
                'parentUrl' => $this->parentUrl
            ));
        } catch (Exception $e) {
            Yii::log("Invalid request. Please do not repeat this request again.");
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
	}

	public function actionDelete()
	{
		$model = Slide::model()->findByPk($_POST['id']);
		if(isset($model)){
			$content = Content::model()->findByPk($model->ContentId);
			if($this->loadModel($_POST['id'])->delete()){
				if(isset($content))
					$content->delete();
				echo CJSON::encode(1);
			}
		}
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		try{
			$model = new Slide();
			$data = $model->getAll();
			$this->render('index',array(
				'data' => $data,
				'parentUrl' => $this->parentUrl));
		}catch(Exception $e){
			echo "Da xay ra loi";
			die;
		}
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Slide('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Slide']))
			$model->attributes=$_GET['Slide'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Slide the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Slide::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Slide $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='slide-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
